﻿using System;
using System.Linq;
using System.Reflection;

namespace Snake.Core
{
    public class DefaultConvention : INamingConvention
    {
        /// <summary>
        /// 获取属性的外键
        /// </summary>
        /// <param name="propertyInfo"></param>
        /// <returns></returns>
        public string GetForeignKeyName(PropertyInfo propertyInfo)
        {
            var name = propertyInfo.Name;
            if (!name.EndsWith("_ID"))
                return propertyInfo.Name + "_ID";

            return name;
        }
        /// <summary>
        /// 传入一个类型 返回这个类型的key
        /// </summary>
        /// <param name="type"></param>
        /// <param name="propertyInfo"></param>
        /// <param name="columnName"></param>
        public void GetKey(Type type, out PropertyInfo propertyInfo, out string columnName)
        {
            var lookingFor = new [] {type.Name + "_ID", type.Name + "ID", "ID"};

            var props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);

            foreach(var prop in props)
            {
                if(prop.CanRead && prop.CanWrite && prop.GetSetMethod(false) != null)
                {
                    if (lookingFor.Any(_ => _.Equals(prop.Name, StringComparison.OrdinalIgnoreCase)))
                    {
                        propertyInfo = prop;
                        columnName = prop.Name;
                        return;
                    }                    
                }
            }
            
            throw new Exception("这个type里面一个鸟都没有 " + type);
        }

        /// <summary>
        /// 获取数据表的名称 ：约腚，类的名称
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public string GetTableName(Type type)
        {
            return type.Name;
        }

       /// <summary>
       /// 获取某一列名：约定，属性和数据表对应
       /// </summary>
       /// <param name="propertyInfo"></param>
       /// <returns></returns>
        public string GetColumnName(PropertyInfo propertyInfo)
        {
            return propertyInfo.Name;
        }
    }
}